package org.cyzy.config;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class InfoQRCodeGenerator {
    public static void main(String[] args) {
        // 整理需要生成二维码的信息
        String info = "id=4ea970e49d5941869f137fe2d895dfe5\n" +
                "name=cyzy\n" +
                "subject=java\n" +
                "grade=2026\n" +
                "description=福州金山校区\n" +
                "semester=9月\n" +
                "coverImage=http://8.141.113.132:9000/test/3.jpg\n" +
                "classCode=611922\n" +
                "teacherId=6";

        // 二维码保存路径：D:\down\info_qrcode.png
        String filePath = "D:\\down\\info_qrcode.png";
        int width = 300;
        int height = 300;
        String format = "png";

        // 确保D:\down目录存在
        File directory = new File("D:\\down");
        if (!directory.exists()) {
            directory.mkdirs(); // 创建目录（包括不存在的父目录）
        }

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);

        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(info, BarcodeFormat.QR_CODE, width, height, hints);

            Path path = new File(filePath).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);

            System.out.println("二维码生成成功，保存路径：" + filePath);
        } catch (WriterException | IOException e) {
            System.out.println("二维码生成失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
